<script lang="ts" setup>
import { type FieldRule, type FormInstance, showFailToast, showSuccessToast } from 'vant'
import { ref } from 'vue'
import { loginPassword, codeGet, loginPost } from '@/api/user'
import { useUserStore } from '@/stores/index'
import { useRouter, useRoute } from 'vue-router'
const route = useRoute()
const userStore = useUserStore()
const router = useRouter()
const show = ref(false)
//
/*
vant表单验证
1:表单元素值双向绑定
2：表单元素绑定规则
3：写规则(手机号：正则验证,密码：8-18位)
4：触发全局表单表单
*/
const mobile = ref('13211112222')
const password = ref('abc12345')
const isAgree = ref(false)

const rules: {
  mobile: FieldRule[]
  password: FieldRule[]
  code: FieldRule[]
} = {
  mobile: [
    { required: true, message: '必填', trigger: 'onChange' },
    { pattern: /^1[3-9]\d{9}$/, message: '请正确输入手机号', trigger: 'onChange' }
  ],
  password: [
    { required: true, message: '必填', trigger: 'onChange' },
    { pattern: /^\w{8,18}$/, message: '请输入8-18位密码', trigger: 'onChange' }
  ],
  code: [
    { required: true, message: '必填', trigger: 'onChange' },
    { pattern: /^\d{6}$/, message: '请输入6位验证码', trigger: 'onChange' }
  ]
}
const form = ref<FormInstance>()
// 登录点击
const submit = async () => {
  await form.value?.validate()
  if (!isAgree.value) {
    // return 提示
    return showFailToast('请先勾选协议!')
  }
  let res
  if (isPassword.value) {
    // 导入与调用登录接口
    res = await loginPassword({
      mobile: mobile.value,
      password: password.value
    })
  } else {
    // 验证码登录  // 获取验证码，验证码倒计时，再登录
    res = await loginPost({
      mobile: mobile.value,
      code: code.value
    })
  }
  // 存储用户信息与token
  userStore.setUserInfo(res.data)
  router.push((route.query.redirect as string) || '/')
}

// 验证码登录切换
const isPassword = ref(true)
const code = ref('')
const time = ref(0)
let timer = -1
// 发送验证码
const sendCode = async () => {
  await form.value?.validate('mobile')
  const res = await codeGet({
    mobile: mobile.value,
    type: 'login'
  })
  showSuccessToast(res.data.code)
  // console.log(res)
  // 倒计时 时间变量   setInterval倒计时 时间为0 不要倒计时了  时间渲染到页面
  time.value = 60
  clearInterval(timer)
  timer = setInterval(() => {
    time.value--
    if (time.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}
</script>

<template>
  <div class="login-page">
    <cp-nav-bar rightText="注册" @click-right="$router.push('/register')" />
    <!-- 头部 -->
    <div class="login-head">
      <h3>{{ isPassword ? '密码登录' : '短信验证码登录' }}</h3>
      <a href="javascript:;" @click="isPassword = !isPassword">
        <span>{{ !isPassword ? '密码登录' : '短信验证码登录' }}</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- 表单 -->
    <van-form autocomplete="off" ref="form">
      <van-field
        :rules="rules.mobile"
        name="mobile"
        v-model="mobile"
        placeholder="请输入手机号"
        type="tel"
      ></van-field>
      <!-- 密码框 -->
      <van-field
        v-if="isPassword"
        :rules="rules.password"
        v-model="password"
        placeholder="请输入密码"
        :type="`${show ? 'text' : 'password'}`"
      >
        <template #right-icon>
          <cp-icon @click="show = !show" :name="`login-eye-${show ? 'on' : 'off'}`" />
        </template>
      </van-field>
      <!-- 短信验证码框 -->
      <van-field v-model="code" :rules="rules.code" v-else placeholder="请输入验证码" type="text">
        <template #button>
          <span class="red" v-if="time === 0" @click="sendCode">发送验证码</span>
          <span class="red" v-else>{{ time }}s后再次发送</span>
        </template>
      </van-field>

      <div class="cp-cell">
        <van-checkbox v-model="isAgree">
          <span>我已同意</span>
          <a href="javascript:;">用户协议</a>
          <span>及</span>
          <a href="javascript:;">隐私条款</a>
        </van-checkbox>
      </div>
      <div class="cp-cell">
        <van-button block round type="primary" @click="submit">登 录</van-button>
      </div>
      <div class="cp-cell">
        <a href="javascript:;">忘记密码？</a>
      </div>
    </van-form>
    <!-- 底部 -->
    <div class="login-other">
      <van-divider>第三方登录</van-divider>
      <div class="icon">
        <img src="@/assets/qq.svg" alt="" />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login {
  &-page {
    padding-top: 46px;
  }
  &-head {
    display: flex;
    padding: 30px 30px 50px;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
    h3 {
      font-weight: normal;
      font-size: 24px;
    }
    a {
      font-size: 15px;
    }
  }
  &-other {
    margin-top: 60px;
    padding: 0 30px;
    .icon {
      display: flex;
      justify-content: center;
      img {
        width: 36px;
        height: 36px;
        padding: 4px;
      }
    }
  }
}
.van-form {
  padding: 0 14px;
  .cp-cell {
    height: 52px;
    line-height: 24px;
    padding: 14px 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    .van-checkbox {
      a {
        color: var(--cp-primary);
        padding: 0 5px;
      }
    }
  }
  .btn-send {
    color: var(--cp-primary);
    &.active {
      color: rgba(22, 194, 163, 0.5);
    }
  }
}
.red {
  color: red;
}
</style>
